package com.kaching.twitter.cron

import java.io.IOException
import javax.servlet.http._
import scala.collection.jcl.Conversions._
import _root_.twitter4j._
import _root_.com.kaching.twitter.PMF
import _root_.com.kaching.twitter.stats.Mentions
import javax.jdo.PersistenceManager
import _root_.com.google.appengine.api.datastore.Key
import _root_.com.google.appengine.api.datastore.KeyFactory
import _root_.javax.jdo.JDOObjectNotFoundException
import scala.util.matching.Regex

class FetchServlet extends HttpServlet {

  override def doGet(req: HttpServletRequest,  resp: HttpServletResponse) : Unit = {
    println("working ")
    val pm : PersistenceManager = PMF.get.getPersistenceManager
    try{
      val mentions = getMentions(pm)
      val twitter = new Twitter(TwitterCredentials.userName, TwitterCredentials.password)
      val tweets = mentions match {
        case null => twitter.getMentions
        case _ => twitter.getMentions(new Paging(mentions.sinceId))
      }
      tweets.reverse.foreach(t => process(twitter, pm, mentions, t))
    } finally {
      pm.close
    }
  }

  def getMentions(pm : PersistenceManager) = {
    val key: Key = KeyFactory.createKey(classOf[Mentions].getSimpleName(), Mentions.singletonKey);
    try {
      val mentions = pm.getObjectById(classOf[Mentions], key)
      println("mentions last id = " + mentions.sinceId)
      mentions
    }
    catch{
      case onf: JDOObjectNotFoundException => {
        println("did not find mentions objects")
        new Mentions(key, 1)
      }
      case e:   Throwable => throw e
    }
  }
  
  implicit def statToTwitterMessage(stat: Status) = TwitterStatusMessage(stat)
  
  def process(twitter: Twitter, pm : PersistenceManager, mentions: Mentions, stat: Status) {
    println("got status : [" + stat.getId + "] " + stat.getText)
    if(stat.getUser.getScreenName == TwitterCredentials.userName){
      println("ignoring my own status")
      return
    }
    val response = KCActor.act(twitter, pm, stat)
    response match {
      case r: ErrorResponse => sendMessage(twitter, stat, response)      
      case r: LinkResquest => sendMessage(twitter, stat, response)
      case _ => twitter.updateStatus(trunk("@" + stat.getUser.getScreenName + " " + response.message), stat.getId)
    }
    mentions.sinceId = stat.getId 
    pm.makePersistent(mentions)
  }
  
  def sendMessage(twitter: Twitter, stat: Status, response: KcResponse) = try{
    twitter.sendDirectMessage(stat.getUser.getScreenName, trunk(response.message))
  } catch {
    case e: TwitterException if e.getMessage.contains("You cannot send messages to users who are not following you") =>
      twitter.updateStatus("@" + stat.getUser.getScreenName + " " + trunk(response.message), stat.getId)
    case other => other.printStackTrace
  }

  private def trunk(str: String) = if(str.length > 140) (str.substring(0, 137) + "...") else str
}